//
//  This file is part of iPhoneSMS.
//
//  iPhoneSMS is free software: you can redistribute it and/or modify
//  it under the terms of the GNU General Public License as published by
//  the Free Software Foundation, either version 3 of the License, or
//  (at your option) any later version.
//
//  iPhoneSMS is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  GNU General Public License for more details.
//
//  You should have received a copy of the GNU General Public License
//  along with iPhoneSMS.  If not, see <http://www.gnu.org/licenses/>.
//
//  SQLite.m
//  iPhoneSMS
//
//  Created by Billy Cahill on 1/30/10.
//  Copyright 2010 Billy Cahill. 
//

#import "SQLite.h"

static int callback(void *sqlite, int argc, char **argv, char **azColName){
	NSMutableArray* ary = (NSMutableArray*)sqlite;
	NSMutableDictionary *lite = [NSMutableDictionary new];
	
	int i;
	for(i=0; i<argc; i++){
		if ( ! argv[i] ) {
			argv[i] = "";
		}
		[lite setObject: [NSString stringWithCString:argv[i]] forKey:[NSString stringWithCString:azColName[i]]];
	}
	
	[ary addObject:lite];
	[lite release];
	
	return 0;
}

@implementation SQLite

-(NSArray*)database:(NSString*)dbloc executeSQL:(NSString*)sql {
	sqlite3 *db = 0;
	char *zErrMsg = 0;
	int rc = 0;
	
	const char* cloc= [dbloc cStringUsingEncoding:1];
	
	rc = sqlite3_open( cloc , &db );
	if( rc ){
		NSLog( @"Can't open database");
		NSLog(dbloc);
		sqlite3_close(db);
		return nil;
	}
	
	NSMutableArray *ary = [[[NSMutableArray alloc] init] autorelease];
	rc = sqlite3_exec(db, [sql cStringUsingEncoding:1], callback, ary, &zErrMsg);
	if( rc!=SQLITE_OK ){
		NSLog(@"SQL Error");
		NSLog( [NSString stringWithCString:zErrMsg]);
		
		sqlite3_free(zErrMsg);
	}
	sqlite3_close(db);
	return ary;
}	

@end
